/*
 * @(#)QueryManager.java Jan 8, 2012 - 3:53:19 PM
 * 
 * Copyright 2011 Cin/UFPE/VSPEED
 */
package br.ufpe.cin.vspeed.query;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import speed2010.middleware.comunicacao.Address;
import speed2010.reformulacao.enums.EnrichmentType;
import speed2010.reformulacao.query.InstanceResult;
import speed2010.reformulacao.query.Query;
import speed2010.reformulacao.query.QueryResult;
import br.ufpe.cin.vspeed.integration.CommunicationManager;

/**
 * @author <a href="mailto:andreza.lba@gmail.com">Andreza Leite de Alencar</a>
 */
public class QueryManager {
	/**
	 * Process the a map with instances results result
	 * 
	 * @param submittedQuery
	 *            - The original query submitted
	 * @param enrichmentVariables
	 *            - A <code>{@link List}<{@link EnrichmentType}></code> with enrichments variables.
	 * @return - A {@code Map<Address, QueryResult>} with results information, using the PI Address as key and
	 *         {@link QueryResult}
	 */
	public Map<Address, QueryResult> executeQueryDL(final String submittedQuery,
			final List<EnrichmentType> enrichmentVariables) {

		final Query query = new Query(submittedQuery, enrichmentVariables);
		final Map<Address, QueryResult> resultMap = CommunicationManager.getInstance().submitQuery(query);

		return resultMap;
	}

	public Map<Integer, InstanceResult> processResults(final Map<Address, QueryResult> resultMap) {
		final Map<Integer, InstanceResult> instancesMap = new LinkedHashMap<Integer, InstanceResult>();

		int instanceCount = 0;
		for (final Entry<Address, QueryResult> entry : resultMap.entrySet()) {
			final Map<String, List<InstanceResult>> peerResults = entry.getValue().getPeersResults();
			for (final Entry<String, List<InstanceResult>> instancesEntry : peerResults.entrySet()) {
				final List<InstanceResult> instancesList = instancesEntry.getValue();
				for (final InstanceResult instanceResult : instancesList) {
					instancesMap.put(instanceCount++, instanceResult);
				}
			}

			final Map<String, List<InstanceResult>> enrichedResults = entry.getValue().getEnrichedResults();
			for (final Entry<String, List<InstanceResult>> instancesEntry : enrichedResults.entrySet()) {
				final List<InstanceResult> instancesList = instancesEntry.getValue();
				for (final InstanceResult instanceResult : instancesList) {
					instancesMap.put(instanceCount++, instanceResult);
				}
			}

		}

		return instancesMap;
	}

	public List<InstanceResult> buildResultsTree(final Map<Integer, InstanceResult> results) {
		final List<InstanceResult> instances = new ArrayList<InstanceResult>();
		for (final Entry<Integer, InstanceResult> entry : results.entrySet()) {
			instances.add(entry.getValue());
		}

		return instances;
	}

}
